package com.lzx.study.controller;

import com.alibaba.cloud.ai.dashscope.audio.DashScopeSpeechSynthesisOptions;
import com.alibaba.cloud.ai.dashscope.audio.synthesis.SpeechSynthesisModel;
import com.alibaba.cloud.ai.dashscope.audio.synthesis.SpeechSynthesisPrompt;
import com.alibaba.cloud.ai.dashscope.audio.synthesis.SpeechSynthesisResponse;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.UUID;

@RestController
public class Text2VoiceController {
    @Resource
    private SpeechSynthesisModel speechSynthesisModel;
    public static final String BAILIAN_VOICE_MODEL = "cosyvoice-v2";
    public static final String BAILIAN_VOICE_TIMBEB = "longyingcui";
    @GetMapping("/t2v/voice")
    public String voice(@RequestParam(name = "msg",defaultValue = "您的余额不足") String msg) throws IOException {
        String filePath = "f:\\voice\\" + UUID.randomUUID() + ".mp3";
        DashScopeSpeechSynthesisOptions dashScopeSpeechSynthesisOptions = DashScopeSpeechSynthesisOptions.builder()
                .model(BAILIAN_VOICE_MODEL)
                .voice(BAILIAN_VOICE_TIMBEB)
                .build();
        SpeechSynthesisResponse response = speechSynthesisModel.call(new SpeechSynthesisPrompt(msg, dashScopeSpeechSynthesisOptions));
        ByteBuffer byteBuffer = response.getResult().getOutput().getAudio();
        FileOutputStream fileOutputStream = new FileOutputStream(filePath);
        fileOutputStream.write(byteBuffer.array());
        return filePath;
    }
}
